package com.yudean.esb.service.impl.erp;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.basic.DateConverter;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.yudean.esb.dao.erp.ErpIdsInsDangerIntDao;
import com.yudean.esb.dao.erp.ErpIdsInsDangerTypeDao;
import com.yudean.esb.dao.erp.ErpIdsInsHeaderIntDao;
import com.yudean.esb.domain.erp.ErpIdsInsDangerInt;
import com.yudean.esb.domain.erp.ErpIdsInsDangerType;
import com.yudean.esb.domain.erp.ErpIdsInsHeaderInt;
import com.yudean.esb.service.ERPInsuranceService;
import com.yudean.esb.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.jws.WebService;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.TimeZone;

import static com.yudean.esb.common.ServiceConstant.*;
import static com.yudean.esb.util.XmlUtil.returnInfo;

/**
 * Created by zenghui on 2015-05-27.
 * desc:
 */
@WebService(endpointInterface = "com.yudean.esb.service.ERPInsuranceService", serviceName = "ERPInsuranceServiceService",targetNamespace = "http://service.esb.yudean.com/")
@Service("erpInsuranceServiceImpl")
@Scope("prototype")
public class ERPInsuranceServiceImpl implements ERPInsuranceService {
    private static final String TAG = "ERPInsuranceServiceImpl";
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(ERPInsuranceServiceImpl.class);
    public static final FastDateFormat ISO_DATE_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd");
    public static final FastDateFormat ISO_DATE_FULL_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");
    @Resource
    private ErpIdsInsHeaderIntDao erpIdsInsHeaderIntDao;
    @Resource
    private ErpIdsInsDangerTypeDao erpIdsInsDangerTypeDao;
    @Resource
    private ErpIdsInsDangerIntDao erpIdsInsDangerIntDao;

    /**
     * @param compCodeStr   公司代码
     * @param startDateStr  生效日
     * @param endDateStr    到期日
     * @param insTypeStr    险种
     * @param insNumberStr  保单号
     * @return              根据公司代码，生效日，到期日，险种，保单号获取公司的保单数据  add by szq
     */
    @Override
    public String getInsuranceData(String compCodeStr, String startDateStr, String endDateStr, String insTypeStr, String insNumberStr) {
        List<ErpIdsInsHeaderInt> list = erpIdsInsHeaderIntDao.getInsuranceData(compCodeStr,
                startDateStr,
                endDateStr,
                insTypeStr,
                insNumberStr);
        // 没有数据的情况下：返回空串
        if (list == null || list.size() < 1) {
            logger.debug("getInsuranceData():no data");
            return returnInfo(PUBLISH_SERVICE, SERVICE_ERP_INSURANCE, ERROR_CODE_NO_DATA);
        }
        logger.debug("getInsuranceData():list:{size:{}}", list.size());
        return this.parseList(list);
    }

    /**
     * @param dangerIntXML 数据
     * @return  写入出险赔付信息
     */
    @Override
    public String putDangerInt(String dangerIntXML) {
        if (StringUtils.isBlank(dangerIntXML)) {
            return returnInfo(EXECUTE_PUT_DATA,SERVICE_DANGER_INT,ERROR_CODE_BLANK_PARAMS);
        }
        try {
            logger.info("ERPInsuranceServiceImpl putDangerInt param in:"+dangerIntXML);
            XStream xstream = new XStream(new DomDriver());
            xstream.registerConverter(new DateConverter("yyyy-MM-dd HH:mm:ss", null,TimeZone.getTimeZone("GMT+8")));
            xstream.alias("ErpIdsInsDangerInt", ErpIdsInsDangerInt.class);
            Document dom = DocumentHelper.parseText(dangerIntXML);
            Element root = dom.getRootElement();
            Element dataList = root.element("data");
            List<ErpIdsInsDangerInt> dangerIntList = new ArrayList<ErpIdsInsDangerInt>();
            for (Iterator i = dataList.elementIterator(); i.hasNext();) {
                Element data = (Element) i.next();
                String eleXml = data.asXML();
                ErpIdsInsDangerInt erpIdsInsDangerInt = (ErpIdsInsDangerInt) xstream.fromXML(eleXml);
                if (erpIdsInsDangerInt.validateNull()) {
                    // 验证数据库非空字段 防止插入数据库出错
                    dangerIntList.add(erpIdsInsDangerInt);
                }
                //erpIdsInsDangerIntDao.insert(erpIdsInsDangerInt);
            }
            logger.info("ERPInsuranceServiceImpl putDangerInt param out:"+dangerIntList);
            erpIdsInsDangerIntDao.insertBatch(dangerIntList);

            return returnInfo(EXECUTE_PUT_DATA, SERVICE_DANGER_INT,SUCCESS);
        } catch (Exception e) {
            return returnInfo(EXECUTE_PUT_DATA, SERVICE_DANGER_INT,e.getMessage());
        }
    }
    // 写入险种信息
    @Override
    public String putDangerType(String dangerTypeXML) {
        if (StringUtils.isBlank(dangerTypeXML)) {
            return returnInfo(EXECUTE_PUT_DATA,SERVICE_DANGER_TYPE,ERROR_CODE_BLANK_PARAMS);
        }
        try {
            logger.info("ERPInsuranceServiceImpl putDangerType param in:"+dangerTypeXML);
            XStream xstream = new XStream(new DomDriver());
            xstream.registerConverter(new DateConverter("yyyy-MM-dd HH:mm:ss", null,TimeZone.getTimeZone("GMT+8")));
            xstream.alias("ErpIdsInsDangerType", ErpIdsInsDangerType.class);
            Document dom = DocumentHelper.parseText(dangerTypeXML);
            Element root = dom.getRootElement();
            Element dataList = root.element("data");
            List<ErpIdsInsDangerType> dangerTypeList = new ArrayList<ErpIdsInsDangerType>();
            for (Iterator i = dataList.elementIterator(); i.hasNext();) {
                Element data = (Element) i.next();
                String eleXml = data.asXML();
                ErpIdsInsDangerType erpIdsInsDangerType = (ErpIdsInsDangerType) xstream.fromXML(eleXml);
                if (erpIdsInsDangerType.validateNull()) {
                    // 验证数据库非空字段 防止插入数据库出错
                    dangerTypeList.add(erpIdsInsDangerType);
                }

                // erpIdsInsDangerTypeDao.insert(erpIdsInsDangerType);
            }
            logger.info("ERPInsuranceServiceImpl putDangerType param out:"+dangerTypeList);
            erpIdsInsDangerTypeDao.insertBatch(dangerTypeList);
            return returnInfo(EXECUTE_PUT_DATA, SERVICE_DANGER_TYPE,SUCCESS);
        } catch (Exception e) {
            return returnInfo(EXECUTE_PUT_DATA, SERVICE_DANGER_TYPE,e.getMessage());
        }
    }

    /**
     * @param insTypeCode   险种编码
     * @return              删除险种信息
     */
    @Override
    public String deleteDangerType(String insTypeCode) {
        if (StringUtils.isBlank(insTypeCode)) {
            return returnInfo(EXECUTE_DEL_DATA,SERVICE_DANGER_TYPE,ERROR_CODE_BLANK_PARAMS);
        }
        try {
            erpIdsInsDangerTypeDao.deleteDangerType(insTypeCode);
            return returnInfo(EXECUTE_DEL_DATA, SERVICE_DANGER_TYPE,SUCCESS);
        } catch (Exception e) {
            return returnInfo(EXECUTE_DEL_DATA, SERVICE_DANGER_TYPE,e.getMessage());
        }
    }

    /**
     * 转换List为XML字符串
     *
     * @param list
     * @return
     */
    private String parseList(List<ErpIdsInsHeaderInt> list) {
        Document doc = null;
        doc = DocumentHelper.createDocument();
        Element root = doc.addElement("service");
        root.addElement("name").setText(PUBLISH_SERVICE);
        root.addElement("type").setText(SERVICE_ERP_INSURANCE);
        Element dataList = root.addElement("data");
        try {
            int size = list.size();
            for (int i = 0; i < size; i++) {
                ErpIdsInsHeaderInt erpIdsInsHeaderInt = list.get(i);
                if (erpIdsInsHeaderInt == null) {
                    continue;
                }
                Element data = dataList.addElement("item");
                this.dataWrapper(erpIdsInsHeaderInt, data);
            }
            return doc.asXML();
        } catch (Exception e) {
            logger.error("parseList():error:" + e.getMessage(), e);
            return returnInfo(PUBLISH_SERVICE,SERVICE_ERP_INSURANCE, e.getMessage());
        }
    }
    /**
     * 将对象装配到Elment中去
     *
     * @param erpIdsInsHeaderInt
     * @param data
     */
    private void dataWrapper(ErpIdsInsHeaderInt erpIdsInsHeaderInt, Element data) {
        data.addElement("insNum").setText(
                StringUtil.convertToString(erpIdsInsHeaderInt.getInsNum()));
        data.addElement("compCode").setText(
                StringUtil.convertToString(erpIdsInsHeaderInt.getCompCode()));
        data.addElement("insNumber").setText(
                StringUtil.convertToString(erpIdsInsHeaderInt.getInsNumber()));
        data.addElement("endOrSementNum").setText(
                StringUtil.convertToString(erpIdsInsHeaderInt.getEndOrSementNum()));
        data.addElement("insType").setText(
                StringUtil.convertToString(erpIdsInsHeaderInt.getInsType()));
        data.addElement("contractCode").setText(
                StringUtil.convertToString(erpIdsInsHeaderInt.getContractCode()));
        data.addElement("contractName").setText(
                StringUtil.convertToString(erpIdsInsHeaderInt.getContractName()));
        data.addElement("startDate").setText(ISO_DATE_FORMAT.format(erpIdsInsHeaderInt.getStartDate()));
        data.addElement("endDate").setText(ISO_DATE_FORMAT.format(erpIdsInsHeaderInt.getEndDate()));
        data.addElement("lastUpdateDate").setText(ISO_DATE_FULL_FORMAT.format(erpIdsInsHeaderInt.getLastUpdateDate()));
        data.addElement("insStatus").setText(
                StringUtil.convertToString(erpIdsInsHeaderInt.getInsStatus()));
        data.addElement("currency").setText(
                StringUtil.convertToString(erpIdsInsHeaderInt.getCurrency()));
        data.addElement("insAssetAmount").setText(
                StringUtil.convertToString(erpIdsInsHeaderInt.getInsAssetAmount()));
        data.addElement("insAmount").setText(
                StringUtil.convertToString(erpIdsInsHeaderInt.getInsAmount()));
        data.addElement("indemnityLimit").setText(
                StringUtil.convertToString(erpIdsInsHeaderInt.getIndemnityLimit()));
        data.addElement("insPsnNum").setText(
                StringUtil.convertToString(erpIdsInsHeaderInt.getInsPsnNum()));
        data.addElement("perPsnAmount").setText(
                StringUtil.convertToString(erpIdsInsHeaderInt.getPerPsnAmount()));
        data.addElement("feeRate").setText(
                StringUtil.convertToString(erpIdsInsHeaderInt.getFeeRate()));
        data.addElement("insFeeCny").setText(
                StringUtil.convertToString(erpIdsInsHeaderInt.getInsFeeCny()));
        data.addElement("insFeeForeign").setText(
                StringUtil.convertToString(erpIdsInsHeaderInt.getInsFeeForeign()));
        data.addElement("exchangeRate").setText(
                StringUtil.convertToString(erpIdsInsHeaderInt.getExchangeRate()));
        data.addElement("feeStatus").setText(
                StringUtil.convertToString(erpIdsInsHeaderInt.getFeeStatus()));
    }
}
